package edu.kit.csl.cratyli.control;

import java.util.HashMap;
import java.util.Map.Entry;

import edu.kit.csl.cratyli.datatypes.Dictionary;
import edu.kit.csl.cratyli.datatypes.TextCorpus;
import edu.kit.csl.cratyli.datatypes.Word;
import edu.kit.csl.cratyli.ui.Logger;

/**
 * This is the trivial reduction strategy. All words with at least one
 * occurrence are written to the new dictionary. All others are removed.
 */
public class OccurrenceReductionStrategy implements ReductionStrategy {

	/* (non-Javadoc)
	 * @see ReductionStrategy#reduce(Dictionary, TextCorpus)
	 */
	@Override
	public Dictionary reduce(Dictionary dict, TextCorpus corpus) {
		Dictionary newDict = new Dictionary();
		HashMap<String, String> newSens = new HashMap<String, String>();
		for (Entry<String, String> entry : corpus) {
			StringBuilder newSen = new StringBuilder();
			for (String corpusWord : entry.getValue().split(" ")) {
				Word word = dict.get(corpusWord);
				if (word == null) {
					Logger.getSingleton().error("Did not find " + corpusWord);
					continue;
				}
				String ortho = word.getOrthographic();
				Word newWord = newDict.get(ortho);
				if (newWord == null) {
					newDict.put(ortho, word);
				} else if (newWord != word) {
					newWord.increaseWeight(word.getWeight());
					word.setWeight(0.0);
				}
				newSen.append(" " + ortho);
			}
			newSens.put(entry.getKey(), newSen.toString().trim());
		}
		corpus.setMap(newSens);
		return newDict;
	}
}
